package main 

import (
	"fmt"
	"os"
	"time"
	"syscall"
	"os/signal"
	"context"
	"net/http"
	"golang.org/x/sync/errgroup"

)

func HandleIndex(w http.ResponseWriter, r *http.Request) {
    r.ParseForm()
    fmt.Println("PATH: ", r.URL.Path)
    fmt.Println("SCHEME: ", r.URL.Scheme)
    fmt.Println("METHOD: ", r.Method)
    fmt.Println()

    fmt.Fprintf(w, "<h1>Index Page</h1>")
}

func main() {
	g, _ := errgroup.WithContext(context.TODO())
	
	srv := http.Server{
		Addr:    ":5672",
		Handler: http.DefaultServeMux,
	}
	http.HandleFunc("/", HandleIndex)

	g.Go(func() error{
		err := srv.ListenAndServe()
		return err
	})

	g.Go(func() error {
		s := make(chan os.Signal)
		signal.Notify(s, syscall.SIGINT, syscall.SIGTERM) //监听 Ctrl+C 信号
	
		<-s
		ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
        defer cancel()
		// shutdown是优雅关闭，close不太优雅
        err := srv.Shutdown(ctx)
		return err
	})

	if err := g.Wait(); err != nil && err != http.ErrServerClosed {
		fmt.Println(err)
	}

	fmt.Println("lifecycle end: already exit....")
}